//
//  WSUserAccountViewModel.swift
//  微博
//
//  Created by 武莎莎 on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import ReactiveCocoa
/// 用户账户视图模型
class WSUserAccountViewModel: NSObject {
    
    // 单例
    static let sharedUserAccount = WSUserAccountViewModel()
    // 用户模型
    var userAccount:WSUserAccount?
    var accessToken:String?{
        return userAccount?.access_token
    }   
    var isLogin:Bool {
        return WSUserAccount.loadUserAccount()?.access_token != nil
    }
    var avatarURL:NSURL? {
        
        guard let urlString = userAccount?.avatar_large else{
            return nil
        }
        return NSURL(string: urlString)
    }

    // 加载access_token 和用户信息
    func loadUserAccount(code:String)->RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
        
            WSNetworkTool.sharedNetworkTool.loadAccessToken(code).doNext({ (result) -> Void in
                let account = WSUserAccount(dict: result as![String:AnyObject])

                self.userAccount = account
                    WSNetworkTool.sharedNetworkTool.loadUserInfo(account.uid!).subscribeNext({ (result) -> Void in
                    
                        let dict = result as! [String: AnyObject]
                        // 设置帐号的属性
                        account.name = dict["name"] as? String
                        account.avatar_large = dict["avatar_large"] as? String
                    
                        printLog(account)
                    
                        // 保存账号
                        account.saveUserAccount()
                    
                        // 通知订阅者网络数据加载完成
                        subscriber.sendCompleted()
                    
                    }, error: { (error) -> Void in
                        subscriber.sendError(error)
                })
 
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })

             return nil
        })
    }
    
    private override init() {
        userAccount = WSUserAccount.loadUserAccount()
    }
    
}
